using System.Threading;
using EmailContacts.ServiceModel.Types;
using MimeKit;
using ServiceStack;
using ServiceStack.OrmLite;
using SmtpClient = MailKit.Net.Smtp.SmtpClient;

namespace EmailContacts.ServiceInterface
{
    /// <summary>
    /// 邮件发送接口
    /// </summary>
    public interface IEmailer
    {
        void Email(Email email);
    }

    public class SmtpEmailer : RepositoryBase, IEmailer
    {
        public SmtpConfig Config { get; set; }
        
        public void Email(Email email)
        {
            var msg = new MimeMessage();
            msg.From.Add(new MailboxAddress(email.From));
            msg.To.Add(new MailboxAddress(email.To));
            msg.Subject = email.Subject;
            
            var plain = new TextPart("plain")
            {
                Text = email.Content
            };

            msg.Body = plain;

            using (var client = new SmtpClient())
            {
                client.Connect(Config.Host, Config.Port, true);

                client.AuthenticationMechanisms.Remove("XOAUTH2");
                client.Authenticate(Config.UserName, Config.Password);
                
                client.Send(msg);

                client.Disconnect(true);
            }

            Db.Save(email);
        }
    }

    public class DbEmailer : RepositoryBase, IEmailer
    {
        public void Email(Email email)
        {
            Thread.Sleep(1000);
            Db.Save(email);
        }
    }
}